#include<sys/types.h>
#include<sys/stat.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<ctype.h>
#include<netdb.h>
#include<netdb.h>
#include<time.h>
#include<fcntl.h>
#include<dirent.h>
#include<getopt.h>
#include<libgen.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
#include<signal.h>
#include"logger.h"
#include<sqlite3.h>
#include"client_sqlite.h"
#include"client_temperature.h"
#include"client_time.h"
#include"client_connect.h"


/*选项说明*/
void   print_usage(char *progname){
        printf("-d(daemon)running background\n");
        printf("-i(--ip):\n");
        printf("-p(--port):\n");
        printf("-t(--time):(eg.:30)\n");
        printf("-h(help):heip information\n");
        printf("\n exampla:%s -d  -p 8888 -t 30 \n",progname);
        return;
}



void print_usage(char *progname);
void signal_stop(int signum);//信号处理
void signal_pip(int signum);
int     g_stop=0;

int main(int argc,char *argv[]){
        int                     socket_fd=-1;
        char                    buf[1024];
        char                    buf_sqlite[1024];
        int                     listen_port;
        int                     opt;
        int                     bytes;
        char                    *ip;
        int                     daemon_run=0;
        struct sockaddr_in      serv_addr;
        float                   temp;
        char                    *hostname;
        struct hostent          *get_ip=NULL;
        char                    *socket_ip;
        char                    T_time[128];
        float                   temperature;
        int                     log_fd;
        int                     stop_time;
        int                     conn_fd;
        int                     rv=-1;
        char                    *zErrMsg;
        time_t                  current_time=0;
        time_t                  last_time=0;
        int                     need_seconds;
        char                    *name="0001";
        pack_info               data;
        sqlite3                 *db;

        /*命令行参数*/
        struct option   opts[]={
        {"daemon",no_argument,NULL,'d'},
        {"ip",required_argument,NULL,'i'},
        {"port",required_argument,NULL,'p'},
        {"time",required_argument,NULL,'t'},
        {"help",no_argument,NULL,'h'},
        {NULL,0,NULL,0},
        };

        while((opt=getopt_long(argc,argv,"di:p:t:h",opts,NULL))!=-1){
                switch(opt){
                        case'd':
                                daemon_run=1;
                                break;
                        case'i':
                                ip=optarg;
                                break;
                        case'p':
                                listen_port=atoi(optarg);
                                break;
                        case't':
                                need_seconds=atoi(optarg);
                                break;
                        case'h':
                                print_usage(argv[0]);
                                return 0;
                        default:
                                break;

                }
        }

        if(!listen_port||!ip){
                print_usage(argv[0]);
                return 0;
        }

        /*日志*/
        if( logger_init("temperature.log", LOG_LEVEL_DEBUG) < 0){
                fprintf(stderr, "initial logger system failure\n");
                return 2;
        }

        /*后台运行*/
        if(daemon_run){
                /*设置守护进程*/
                 if ((daemon(1, 1)) < 0){
                    //printf("Deamon failure : %s\n", strerror(errno));
                      log_error("This is error level message!");
                      return 0;
                }
                printf("Program %s is running at the background now\n",argv[0]);
                }

        signal(SIGTERM,signal_stop);
        signal(SIGPIPE,signal_pip);

        /*创建数据库，若成功则创建表，失败则删除库*/
        sqlite_open_create(db);

        /*socket*/
        conn_fd=client_connect(ip,listen_port);

        current_time = 0;
        while(!g_stop){
                check_flag=0;
                /*控制采样时间*/
                current_time = time(NULL);
                if((current_time - last_time) >= need_seconds)
                {   /*获取采样温度*/
                        get_temperature(&temperature);
                        if(temperature<0){
                                printf("read temperature failure:%s\n",strerror(errno));
                                check_flag=0;
                                continue;

                        }
                        printf("read temperature successful\n");

                        get_time(T_time);
                        if(T_time<0){
                                printf("get time failure:%s\n",strerror(errno));
                                check_flag=0;
                                continue;

                        }
                        printf("get time successful\n");
                        memset(&data,0,sizeof(data));
                        strcpy(data.name,"0001");
                        strncpy(data.T_time,T_time,sizeof(T_time));
                        data.temperature=temperature;
                        pack_data(data,buf,sizeof(buf));
                        printf("buf=%s\n",buf);
                        last_time = current_time;
                        check_flag=1;
                }

                /*获取套接字，尝试重新连接并将数据存入数据库*/
                if(conn_fd<0){
                        client_connect(ip,listen_port);
                        if(conn_fd<0){
                                printf("disconnect again\n");
                                close(conn_fd);

                                if(check_flag){
                                        sqlite_insert(db,buf);
                                }
                        }
                }
                else {
                        if(check_flag){

                                if(write(conn_fd,buf,sizeof(buf))<0){
                                    printf("write data to server failure:%s\n",strerror(errno));
                                    close(conn_fd);
                                }
                                else{
                                    printf("write data successful!\n");

                                    /*连接成功并且成功获取数据，客户端向服务器端发送数据库*/
                                    sqlite_get(db,buf_sqlite);
                                    printf("buf_sqlite=%s\n",buf_sqlite);
                                    if(!buf_sqlite){
                                        printf("buf_sqlite have no data\n");
                                    }
                                    /*传数据库暂存内容*/
                                    else if(write(conn_fd,buf_sqlite,strlen(buf_sqlite))<0){
                                            printf("write sqlite to server failure:%s\n",strerror(errno));
                                            close(conn_fd);
                                    }
                                    printf("write buf_sqlite successful!\n");
                                    sqlite_delete(db);
                                    }
                        }

                    
                }

        logger_term();
        sqlite3_close(db);
        return 0;
}



/*信号*/
void signal_stop(int signum){

        if(SIGTERM==signum){
                printf("SIGTERM signal detected\n");
                g_stop=1;
        }
}
void signal_pip(int signum){

         if(SIGPIPE==signum){
                printf("SIGPIPE signal detected\n");
        }
}



/*
                     
                                if(write(conn_fd,buf,sizeof(buf))<0){
                                        printf("write data to server failure:%s\n",strerror(errno));
                                        goto cleanup;
                                }
                                else{
                                        printf("write data successful!\n");

                                    
                                        sqlite_get(db,buf_sqlite);
                                        if(!buf_sqlite){
                                                printf("buf_sqlite have no data\n");
                                        }
                                        
                                        else if(write(conn_fd,buf_sqlite,strlen(buf_sqlite))<0){
                                                printf("write sqlite to server failure:%s\n",strerror(errno));
                                                goto cleanup;
                                        }
                                        else{
                                                printf("write buf_sqlite successful!\n");
                                                sqlite_delete(db);
                                        }
                                }
*/
